package cn.com.easyfelling;

import cn.com.easyfelling.dao.AccountDao;
import cn.com.easyfelling.entity.Account;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.builder.xml.XMLConfigBuilder;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.*;
import org.apache.ibatis.transaction.Transaction;
import org.apache.logging.log4j.core.config.xml.XmlConfiguration;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@Slf4j
public class MybatisTestInfo {
  /**
   * 测试方法：传统方式
   */
  @org.junit.Test
  public void test() throws IOException {
    // 1.
    InputStream resourceAsStream =
      Resources.getResourceAsStream("sqlMapConfig.xml");
    // 2.1 解析了配置文件，封装configration对象
    // 2.2 创建了DefaultSqlSessionFactory工厂对象
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream,"test");

    //3. openSession 执行的逻辑是什么？
    // 3.1 创建事务对象
    // 3.2 创建了执行器对象cachingExecutor
    // 3.3 创建了DefaultSqlSession对象X
    SqlSession sqlSession = sqlSessionFactory.openSession();

    //4. 执行sql语句
    // 缓存流程：(1)生成CacheKey对象 (2) 从缓存中获取Cache对象 (3) 执行查询操作 (4) 封装Cache对象 (5) 存入缓存中
    // 委派给Executor执行器对象来执Type行，Executor会调用很多其他组件(参数设置，解析sql的获取，sql执行,结果集的封装)
    User user = sqlSession.selectOne("cn.com.easyfelling.User.findUserById", 1);

    System.out.println(user);
    // 5. 关闭sqlSession
    sqlSession.close();
  }

  @Test
  public void testExecutor() throws Exception {
    // 1.
    InputStream resourceAsStream =
      Resources.getResourceAsStream("sqlMapConfig.xml");
    XMLConfigBuilder xmlConfigBuilder = new XMLConfigBuilder(resourceAsStream);
    Configuration configuration = xmlConfigBuilder.parse();

    Transaction transaction = configuration.getEnvironment().getTransactionFactory().newTransaction(configuration.getEnvironment().getDataSource(), TransactionIsolationLevel.READ_COMMITTED, false);

    Executor executor =configuration.newExecutor(transaction, ExecutorType.SIMPLE);
    executor.update(configuration.getMappedStatement("user.addUser"), null);

  }
  @Test
    public void testPageHelper() throws IOException {
    // 1.
    InputStream resourceAsStream =
      Resources.getResourceAsStream("sqlMapConfig.xml");
    // 2.1 解析了配置文件，封装configration对象
    // 2.2 创建了DefaultSqlSessionFactory工厂对象
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream,"test");

    //3. openSession 执行的逻辑是什么？
    // 3.1 创建事务对象
    // 3.2 创建了执行器对象cachingExecutor
    // 3.3 创建了DefaultSqlSession对象X
    SqlSession sqlSession = sqlSessionFactory.openSession();

    AccountDao dao = sqlSession.getMapper(AccountDao.class);
    PageHelper.startPage(1,2);
    List<Account> list = dao.query();
    System.out.println(list);
    sqlSession.close();

  }

}
